<template>
  <a-modal v-model:open="isShow" title="重新设定密码" @cancel="handleCancelPassword" style="width: 700px">
    <a-form ref="form" :model="formState" :rules="rules" style="margin-top: 30px" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
      <a-form-item label="用户账户" name="username">
        <a-input v-model:value="formState.username" readOnly />
      </a-form-item>
      <a-form-item  label="登录密码" name="password">
        <a-input v-model:value="formState.password" type="password" autocomplete="off" />
      </a-form-item>
      <a-form-item  label="确认密码" name="confirmpassword">
        <a-input v-model:value="formState.confirmpassword" type="password" autocomplete="off" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancelPassword">取消</a-button>
      <a-button type="primary" :loading="btnLoading" @click="handlePassword">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import {changePassword} from "@/api/system/user.js";
import {message} from "ant-design-vue";
const form = ref()
const btnLoading = ref(false)
const emit = defineEmits(['close'])
const props = defineProps({
  openPassword: {
    type: Boolean,
    default: false
  },
  username:{
    type: String,
    default: ''
  }
})
const formState = reactive({
  username: '',
  password: '',
  confirmpassword: ''
})
const isShow = computed(() => {
  return props.openPassword
})
/**
 * 取消密码修改
 */
const handleCancelPassword = () => {
  emit('close')
  form.value.resetFields()
}
/**
 * 密码校验
 * @param rule
 * @param value
 * @returns {Promise<never>|Promise<void>}
 */
const compareToFirstPassword  = (rule, value) => {
  console.log(value)
  if (value && value !== formState.password) {
    return Promise.reject('两次输入的密码不一样！');
  } else {
    return Promise.resolve();
  }
}
/**
 * 修改密码
 */
const handlePassword = () => {
  form.value.validate().then(async() => {
    btnLoading.value = true
    const res = await changePassword(formState)
    if(res.success){
      message.success(res.message);
      emit('close')
      form.value.resetFields()
      btnLoading.value = false
    }else{
      btnLoading.value = false
      message.warning(res.message);
    }
  }).catch(err=>{
    console.log('err', err)
    btnLoading.value = false
  })
}

const rules = {
  password: [
    {required: true,trigger: 'change',
      pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
      message: '密码由8位数字、大小写字母和特殊符号组成!'
    },
  ],
  confirmpassword: [
    {required: true, message: '请重新输入登录密码!',},
    { validator: compareToFirstPassword, trigger: 'change'}
  ],
}
onMounted(() => {
  formState.username = props.username
})
</script>
<style scoped>

</style>
